package com.zmn.oms.admin.controller.work.list;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.data.LayuiTableDO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.office.excel.ExportExcel;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.common.constant.OmsPageConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.vo.TabQueryVO;
import com.zmn.oms.model.entity.work.list.OrderWorkMemberQuery;
import com.zmn.oms.model.vo.work.list.ZsOrderWorkMemberExportVO;
import com.zmn.oms.model.vo.work.list.ZsOrderWorkMemberVO;
import com.zmn.oms.zmn.business.interfaces.work.list.ZsOrderWorkMemberQueryBService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：会员工单列表controller
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@RequestMapping("/member/work")
public class WorkMemberListController extends WorkListTabBaseController {

    private static final Logger logger = LoggerFactory.getLogger(WorkMemberListController.class);

    @Autowired
    ZsOrderWorkMemberQueryBService zsOrderWorkMemberQueryBService;

    private static final String TAB_ONE_NAME = "待工程师审核";
    private static final String TAB_TWO_NAME = "审核失败";
    private static final String TAB_THREE_NAME = "待回访";
    private static final String TAB_FOUR_NAME = "有投诉";
    private static final String TAB_FIVE_NAME = "待平台审核";

    private static LinkedHashMap<String, String> fieldMap = Maps.newLinkedHashMap();
    static {
        fieldMap.put("receiveTime", "下单时间");
        fieldMap.put("dutyTime", "预约时间");
        fieldMap.put("distributeTime", "派单时间");
        fieldMap.put("visitTime", "上门时间");
        fieldMap.put("completeTime", "完成时间");
        fieldMap.put("resultTimeCallback", "取消时间");
        fieldMap.put("companyName", "子公司");
        fieldMap.put("naturalCityName", "城市");
        fieldMap.put("orderId", "订单号");
        fieldMap.put("userNameCallback", "用户");
        fieldMap.put("servCategName", "服务分类");
        fieldMap.put("categTwoName", "服务品类");
        fieldMap.put("typeName", "返修新单");
        fieldMap.put("originalIdCallBack", "源单号");
        fieldMap.put("isMemberCallback", "会员订单/普通订单");
        fieldMap.put("equtityTypeName", "会员权益");
        fieldMap.put("originalAmountCallback", "订单金额");
        fieldMap.put("discountAmountCallback", "优惠");
        fieldMap.put("totalAmountCallback", "订单收入");
        fieldMap.put("reviewStatusName", "审核状态");
        fieldMap.put("masterNameCallback", "工程师");
        fieldMap.put("statusName", "状态");
        fieldMap.put("isReplyCallback", "回访");
        fieldMap.put("saleMasterNameCallback", "销售工程师");
    }

    /**
     * 工单列表
     */
    @RequiresPermissions("/zs/member/work/list.action")
    @RequestMapping(value = "/list")
    public ModelAndView list(ModelAndView mv, OrderWorkMemberQuery defaultQuery, String queryView) {
        mv.setViewName("work/list/member/list");

        // 默认显示查询条件
        if (Objects.isNull(queryView)) {
            queryView = "precisionQuery";
        }
        mv.addObject("hideQueryView", GlobalConsts.NO);
        // 评星
        mv.addObject("scoreList", OrderConsts.getCommentScoreList());

        super.setDayLimit(mv);
        super.setDefaultModelAndView(mv);

        List<TabQueryVO> tabList = Lists.newArrayList();
        OrderWorkMemberQuery query = new OrderWorkMemberQuery();
        query.setDeptId(getDeptId());

        // 精准查询
        if (StaffAdminService.isPermitted("/zs/member/work/list/precision/query.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_PRECISION).tabTypeName(OmsPageConsts.QUERY_TAB_PRECISION_NAME)
                    .queryView(OmsPageConsts.QUERY_TAB_PRECISION_VIEW_NAME).autoQuery(GlobalConsts.NO).build());
        }
        // 待平台审核
        if (StaffAdminService.isPermitted("/zs/member/work/query/waitplatreview.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_WAIT_PLAT).tabTypeName(OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_WAIT_PLAT_NAME).build());
        }
        // 审核失败 数量
        if (StaffAdminService.isPermitted("/zs/member/work/query/reviewfail.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_FAIL).tabTypeName(OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_FAIL_NAME).build());
        }
        // 待回访 数量
        if (StaffAdminService.isPermitted("/zs/member/work/query/waitreply.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_WAIT_VISIT).tabTypeName(OmsPageConsts.QUERY_TAB_WAIT_VISIT_NAME).build());
        }
        // 有投诉数量
        if (StaffAdminService.isPermitted("/zs/member/work/query/complaint.action")) {
            tabList.add(TabQueryVO.builder().tabType(OmsPageConsts.QUERY_TAB_COMPLAINT).tabTypeName(OmsPageConsts.QUERY_TAB_COMPLAINT_NAME).build());
        }

        mv.addObject("tabList", tabList);
        mv.addObject("queryView", queryView);

        // 默认日期
        mv.addObject("startTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 00:00:00"));
        mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd 23:59:59"));

        // 查询条件
        mv.addObject("query", defaultQuery);
        return mv;
    }

    /**
     * 工单列表 ajax
     */
    @RequiresPermissions("/zs/member/work/list.action")
    @PostMapping(value = "/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@NotNull @RequestBody OrderWorkMemberQuery query) {

        // 处理tab查询
        processTagTypeQuery(query);

        // 处理查询条件
        processSearchQuery(query);

        List<ZsOrderWorkMemberVO> voList = zsOrderWorkMemberQueryBService.listPageOrderWorkByQuery(query);
        LayuiTableDO<ZsOrderWorkMemberVO> data = new LayuiTableDO<>();
        data.setCount(query.getTotalCount());
        data.setData(voList);
        return ResultDTO.success(data);
    }

    /**
     * 工单,单条 ajax
     */
    @RequiresPermissions("/zs/member/work/list.action")
    @GetMapping(value = "/ajax/row")
    @ResponseBody
    public ResultDTO ajaxRow(@Valid OrderWorkMemberQuery query) {
        List<ZsOrderWorkMemberVO> voList = zsOrderWorkMemberQueryBService.listPageOrderWorkByQueryNoRecord(query);
        return ResultDTO.success(voList.get(0));
    }

    /**
     * 处理tab 查询
     * @param query
     */
    private void processTagTypeQuery(OrderWorkMemberQuery query){

       // "待审核"; "审核失败";"待回访";"有投诉";
        Integer tabType = query.getTabType();
        if (tabType != null) {
            switch (tabType) {
                case OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_FAIL:
                    List<Integer> reviewFailStatusList = Arrays.asList(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_MASTER_FAIL, OrderConsts.ORDER_MEMBER_REVIEW_STATUS_PLAT_FAIL);
                    // 审核失败
                    query.setReviewStatusList(reviewFailStatusList);
                    break;
                case OmsPageConsts.QUERY_TAB_WAIT_VISIT:
                    // 待回访
                    query.setReplyVisited(GlobalConsts.NO);
                    break;
                case OmsPageConsts.QUERY_TAB_COMPLAINT:
                    // 有投诉
                    query.setComplaintStatus(GlobalConsts.YES);
                    break;
                case OmsPageConsts.QUERY_TAB_MEMBER_REVIEW_WAIT_PLAT:
                    // 待平台审核
                    query.setReviewStatusList(Arrays.asList(OrderConsts.ORDER_MEMBER_REVIEW_STATUS_WAIT_PLAT));
                    query.setWorkStatus(Lists.newArrayList(OrderStatusConsts.WORK_STATUS_VISIT));
                    query.setWorkResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
                    break;
                default:
                    // 不处理
            }
        }
    }

    @RequestMapping(value = "/exportexcel")
    public void exportExcel(OrderWorkMemberQuery query, HttpServletResponse response)
            throws Exception {

        // 导出最多两千条
        query.setPageSize(5000);

        // 处理tab查询
        processTagTypeQuery(query);

        // 处理查询条件
        processSearchQuery(query);

        List<ZsOrderWorkMemberExportVO> voList = zsOrderWorkMemberQueryBService.exportOrderWorkByQuery(query);

        ExportExcel<ZsOrderWorkMemberExportVO> excel = new ExportExcel(voList, fieldMap, true);

        excel.setCallback((fieldName, entity) -> {
            switch (fieldName) {
                case "resultTimeCallback":
                    if (Objects.equals(entity.getResultStatus(), OrderStatusConsts.WORK_RESULT_DISCARD) && entity.getResultTime() != null) {
                        return DateUtil.dateFormatToString(entity.getResultTime(), DateUtil.FORMAT_DEFAULT);
                    }
                    break;
                case "userNameCallback":
                    String userName = entity.getUserName();
                    String hideMobile = StringUtil.formatHideMobile(entity.getUserPhone());
                    return userName + ":" + hideMobile;
                case "isMemberCallback":
                    return (entity.getIsMember() != null && entity.getIsMember()) ? "会员单" : "普通单";
                case "originalIdCallBack":
                    return (entity.getOriginalId() != null && entity.getOriginalId() != 0) ? String.valueOf(entity.getOriginalId()) : "";
                case "originalAmountCallback":
                    return  MoneyUtil.parseToYuanStr(entity.getOriginalAmount());
                case "discountAmountCallback":
                    return  MoneyUtil.parseToYuanStr(entity.getDiscountAmount());
                case "totalAmountCallback":
                    return  MoneyUtil.parseToYuanStr(entity.getTotalAmount());
                case "isReplyCallback":
                    return  (entity.getIsReply() != null && entity.getIsReply()) ? "已回访" : "未回访";
                case "masterNameCallback":
                    String masterName = entity.getMasterName();
                    if (StringUtil.isNotBlank(masterName)) {
                        String hideMasterMobile = StringUtil.formatHideMobile(entity.getMasterPhone());
                        return masterName + ":" + hideMasterMobile;
                    }
                    break;
                case "saleMasterNameCallback":
                    String saleMasterName = entity.getSaleMasterName();
                    if (StringUtil.isNotBlank(saleMasterName)) {
                        String hideSaleMasterMobile = StringUtil.formatHideMobile(entity.getSaleMasterPhone());
                        return saleMasterName + ":" + hideSaleMasterMobile;
                    }
                    break;
                default:
                    break;
            }
            return null;
        });
        excel.exportExcel(response, "会员工单");
    }

    /**
     * 处理查询条件
     *
     * @param query
     */
    private void processSearchQuery(OrderWorkMemberQuery query) {

        query.setIsSensitiveAddr(true);
        query.setIsSensitiveTel(true);

        // 查询服务平台是啄木鸟的
        query.setPlatWork(GlobalConsts.PLAT_MARK_ZMN);

        // 查询手机号对应的用户
        query.setQueryConcatPhoneUsers(true);
    }

}